package lt.startup.duobes;

import java.util.ArrayList;

import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.location.Location;
import android.util.Log;

public class Sender {
	
	private static final String URL = "http://www.duobes.lt/duobesapi/handler.php?action=put"; 

	private HttpClient httpClient = new DefaultHttpClient();	
	private ArrayList<LocPoint> array = new ArrayList<LocPoint>();
	private boolean sending;
	
	private class LocPoint{
		public double lat;
		public double lng;
		public double course;
		public double value;
		public double speed;
	}
	
	public Sender(){
		sending = false;
	}
	
	public int amount(){
		return array.size();
	}
	
	public void addPoint(Location loc, double value){
		LocPoint point = new LocPoint();
		point.lat = loc.getLatitude();
		point.lng = loc.getLongitude();
		point.course = loc.getBearing();
		point.speed = loc.getSpeed();
		point.value = value;
		array.add(point);
	}
	
	public void sendPoints(){
		if (!sending){
			try {
				sending = true;
				HttpPost httppost = new HttpPost(URL);
				ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
				JSONObject object = new JSONObject();
				JSONArray jsonArray = new JSONArray();
				for (final LocPoint point: array){
					JSONObject obj = new JSONObject();
					obj.put("lat", point.lat);
					obj.put("lng", point.lng);
					obj.put("course", point.course);
					obj.put("speed", point.speed);
					jsonArray.put(obj);				
				}
				array.clear();
				object.put("potholes", jsonArray);
				object.put("device", Constants.id);	
				
				final String json = object.toString();
				pairs.add(new BasicNameValuePair("data", json));
				Log.i("data", json);
				httppost.setEntity(new UrlEncodedFormEntity(pairs));		
				httpClient.execute(httppost);
				sending = false;				
			} catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	
}
